package cosplay.controller;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import cosplay.DAO.UserDAOImpl;
import cosplay.beans.Users;
@Controller
public class UserController extends MultiActionController {
	@Autowired
	private UserDAOImpl userdao;

	@RequestMapping(value="/useradmin.htm",method=RequestMethod.GET)
	protected ModelAndView handleshowadmin(HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
		// TODO Auto-generated method stub
		int pagesize=4;
		List<Users> user=userdao.getAll();
		ModelMap model=new ModelMap();
		model.addAttribute("user", user);
		int resultcount=user.size();
		model.addAttribute("resultcount",resultcount);
		model.addAttribute("pagesize",pagesize);
		int pagecount= (resultcount/pagesize);
		if ((resultcount%pagesize)>0)
			pagecount=pagecount+1;
		model.addAttribute("pagecount",pagecount);
		return new ModelAndView("userlist","model",model);
	}
	@RequestMapping(value="/usermodify.htm",method=RequestMethod.GET)
	protected ModelAndView handleshowmodify(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		// TODO Auto-generated method stub
		String name="";
		int id=0;
		String role=SecurityContextHolder.getContext().getAuthentication().getAuthorities()[0].getAuthority();
		if (role.equals("ROLE_USER"))
		{
			name=SecurityContextHolder.getContext().getAuthentication().getName();
			id=userdao.getByName(name).getId();
		}
		if (role.equals("ROLE_ADMIN"))
		{
			id=Integer.valueOf(req.getParameter("id")).intValue();
		}
		//id= Integer.valueOf(req.getParameter("id")).intValue();
		Users user=userdao.get(id);
		ModelMap model=new ModelMap();
		model.addAttribute("user", user);
		return new ModelAndView("usermodify","model",model);
	}
	@RequestMapping(value="/usermodify.htm",method=RequestMethod.POST)
	protected ModelAndView handleactmodify(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		// TODO Auto-generated method stub
		//SavedRequestAwareWrapper sraw =(SavedRequestAwareWrapper) req; 
		MultipartHttpServletRequest request=(MultipartHttpServletRequest)((HttpServletRequest) req);
		Users user=getUserFromReq(request);
		String name="";
		int id=0;
		String role=SecurityContextHolder.getContext().getAuthentication().getAuthorities()[0].getAuthority();
		if (role.equals("ROLE_USER"))
		{
			name=SecurityContextHolder.getContext().getAuthentication().getName();
			id=userdao.getByName(name).getId();
		}
		if (role.equals("ROLE_ADMIN"))
		{
			id=Integer.valueOf(req.getParameter("id")).intValue();
		}
		user.setId(id);
		userdao.edit(user, id);
		ModelMap model=new ModelMap();
		model.addAttribute("user", user);
		model.addAttribute("message", "Successed");
		return new ModelAndView("usermodify","model",model);
	}
	@RequestMapping(value="/register.htm",method=RequestMethod.GET)
	protected ModelAndView handleshowregist(HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
		// TODO Auto-generated method stub
		return new ModelAndView("register");
	}
	@RequestMapping(value="/register.htm",method=RequestMethod.POST)
	protected ModelAndView handleactregist(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		// TODO Auto-generated method stub
		//SavedRequestAwareWrapper sraw =(SavedRequestAwareWrapper) req; 
		MultipartHttpServletRequest request=(MultipartHttpServletRequest)((HttpServletRequest) req);
		userdao.add(getUserFromReq(request));
		res.sendRedirect("welcome.htm");
		return null;
	}
	private Users getUserFromReq(MultipartHttpServletRequest req)
	{
		Users user=new Users();
		if((req.getParameter("username")==null)||(req.getParameter("username").equals("")))
			return null;
		if((req.getParameter("password")==null)||(req.getParameter("password").equals("")))
			return null;
		user.setAddress(req.getParameter("address"));
		user.setBirthday(req.getParameter("birthday"));
		user.setCountry(req.getParameter("country"));
		user.setDescription(req.getParameter("description"));
		user.setEmail(req.getParameter("email"));
		try {
			if(req.getFileMap().containsKey("headimage"))
			user.setHeadImage(cosplay.Services.FileServices.getpreview(req.getFile("headimage").getBytes()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		user.setLastLogIP(req.getRemoteAddr());
		user.setNickName(req.getParameter("nickname"));
		user.setPassWord(req.getParameter("password"));
		user.setTel(req.getParameter("tel"));
		user.setUserName(req.getParameter("username"));
		if((req.getParameter("userrole")==null)||(req.getParameter("userrole").equals("")))
			user.setUserRole("ROLE_USER");
		else
			user.setUserRole(req.getParameter("userrole"));
		return user;
	}

}
